package br.loja.filters;

import java.io.IOException;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;

import br.loja.enumerators.ConexaoEnum;

@WebFilter(servletNames = { "Faces Servlet" })
public class JPAFilter implements Filter {

	private EntityManagerFactory emf;

	@Override
	public void destroy() {
		this.emf.close();
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		EntityManager manager = this.emf.createEntityManager();

		try {
			manager.getTransaction().begin();
			chain.doFilter(request, response);
			manager.getTransaction().commit();
			manager.close();
		} catch (Throwable t1) {
			try {
				if (manager.getTransaction().isActive()) {
					manager.getTransaction().rollback();
				}
			} catch (Throwable t2) {
				t2.printStackTrace();
			}
			t1.printStackTrace();
		}
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		this.emf = Persistence
				.createEntityManagerFactory(ConexaoEnum.PERSISTENCE_UNIT
						.getValor());
	}
}
